#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.parse_parafile import get_env_variable
from common.common import check_command_injection_ex
from generaldb.saphana.comm.saphana_const import SaphanaJsonConstant, SaphanaMetadataKey
from generaldb.saphana.comm.saphana_parse_job_param_base import SaphanaParseJobParamsBase
from generaldb.saphana.comm.common_util import log


class SaphanaParseBackupParam(SaphanaParseJobParamsBase):
    def __init__(self, pid, job_id, subjob_id):
        super(SaphanaParseBackupParam, self).__init__(pid, job_id, subjob_id)

    def get_all_repositories(self):
        return self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.REPOSITORIES, [])

    def get_backup_type(self):
        """
        获取备份类型：全量/增量/差异/日志
        """
        return self._json_param.get(SaphanaJsonConstant.JOB, {}). \
            get(SaphanaJsonConstant.JOB_PARAM, {}).get(SaphanaJsonConstant.BACKUP_TYPE)

    def get_backup_db_name(self):
        """
        获取待备份的数据库名称
        """
        return self._json_param.get(SaphanaJsonConstant.JOB, {}). \
            get(SaphanaJsonConstant.PROTECT_OBJECT, {}).get(SaphanaJsonConstant.NAME, "")

    def get_backup_db_user(self):
        """
        获取待备份的数据库的用户名
        """
        user_env = f"{SaphanaJsonConstant.JOB}_{SaphanaJsonConstant.PROTECT_OBJECT}_{SaphanaJsonConstant.AUTH}_" \
                   f"{SaphanaJsonConstant.AUTH_KEY}_{self._pid}"
        return get_env_variable(user_env)

    def get_system_db_info(self):
        """
        获取系统数据库自定义参数：当目标数据库为系统数据库时，直接取protectEnv.auth.authKey; 当目标数据库为租户数据库时，取
        protectEnv.auth.extendInfo.auth.authKey
        """
        info_env = f"{SaphanaJsonConstant.JOB}_{SaphanaJsonConstant.PROTECT_OBJECT}_" \
                   f"{SaphanaJsonConstant.AUTH}_" \
                   f"{SaphanaJsonConstant.EXTEND_INFO}_{SaphanaJsonConstant.AUTH_CUSTOM_PARAMS}_{self._pid}"
        return get_env_variable(info_env).strip("\n")

    def get_all_agents_ip(self):
        """
        获取用户选择的所有代理主机的所有IP地址
        例子：”xxx.xxx.xxx.xxx,xxx.xxx.xxx.xxx; xxx.xxx.xxx.xxx, xxx.xxx.xxx.xxx“
        """
        all_nodes = self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.PROTECT_ENV, {}). \
            get(SaphanaJsonConstant.NODES, [])
        ret_ip_list = []
        for node in all_nodes:
            agent_ip_list_str = node.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaJsonConstant.AGENT_IP_LIST, "")
            ret_ip_list.append(agent_ip_list_str)
        return ret_ip_list

    def get_all_agents_register_ip(self):
        """
        获取用户选择的所有代理主机注册的IP
        """
        all_nodes = self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.PROTECT_ENV, {}). \
            get(SaphanaJsonConstant.NODES, [])
        ip_list = []
        for node in all_nodes:
            temp_ip = node.get(SaphanaJsonConstant.ENDPOINT, "")
            if not temp_ip:
                continue
            ip_list.append(temp_ip)
        return ip_list

    def get_self_define_param(self):
        return self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.PROTECT_OBJECT, {}) \
            .get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaJsonConstant.CUSTOM_PARAMS, "").strip("\n")

    def get_backup_result(self):
        return self._json_param.get(SaphanaJsonConstant.BACK_JOB_RESULT)

    def get_protect_object(self):
        return self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.PROTECT_OBJECT, {})

    def get_deploy_type(self):
        return self._json_param.get(SaphanaJsonConstant.JOB, {}).get(SaphanaJsonConstant.PROTECT_OBJECT, {})\
                .get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaJsonConstant.DEPLOY_TYPE, "")


class SaphanaCopyInfoParam:

    @staticmethod
    def get_db_info(param):
        return param.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaMetadataKey.DB_INFO, {})

    @staticmethod
    def get_system_attr(param):
        return param.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaMetadataKey.MULTI_TENANT_SYSTEM, None)

    @staticmethod
    def get_backup_log_position(param):
        return param.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaMetadataKey.BACKUP_LOG_POSTION, 0)

    @staticmethod
    def get_backup_timestamp(param):
        return param.get(SaphanaJsonConstant.TIMESTAMP, 0)

    @staticmethod
    def get_backup_id(param):
        backup_id = param.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaMetadataKey.BACKUP_ID, 0)
        if isinstance(backup_id, str) and check_command_injection_ex(backup_id):
            log.error(f"Backup id injection.")
            return 0
        return int(backup_id)

    @staticmethod
    def get_last_backup_hostname(param):
        return param.get(SaphanaJsonConstant.EXTEND_INFO, {}).get(SaphanaMetadataKey.BACKUP_HOSTNAME, 0)
